#include <gtk/gtk.h>
#include <gtk/gtkgl.h>
#include <gdk/gdkgl.h>
#include <X11/Xlib.h>
#include "mediaplayer.h"

mp_t			*mp;
GtkWidget		*window;
GtkWidget		*hbox, *vbox;
GtkWidget		*button;

static void destroy(GtkWidget *widget, gpointer data) {
	if (mp_is_playing(mp)) mp_stop(mp);
	mp_close(mp);
	mp_free	(mp);
	gtk_main_quit();
}

static void open(GtkWidget *widget, gpointer data) {
	GtkWidget *dialog = gtk_file_chooser_dialog_new("Open File",
		window,
		GTK_FILE_CHOOSER_ACTION_OPEN,
		GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
		GTK_STOCK_OPEN	, GTK_RESPONSE_ACCEPT,
		NULL
	);

	if(gtk_dialog_run(dialog) == GTK_RESPONSE_ACCEPT) {
		char *filename;
		filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER (dialog));

		mp_close(mp);
		mp_load(mp, filename);
		if (mp_num_streams(mp, CODEC_TYPE_AUDIO) > 0) mp_setup_stream(mp, 0, PLAYER_AUDIO_ALSA	, NULL);
		if (mp_num_streams(mp, CODEC_TYPE_VIDEO) > 0) mp_setup_stream(mp, 0, PLAYER_VIDEO_GTK	, vbox);
		mp_open(mp);

		g_free(filename);
	}
	gtk_widget_destroy(dialog);
}

static void play(GtkWidget *widget, gpointer data) {
	mp_t *mp = data;
	if (mp_is_playing(mp)) mp_stop(mp);
	mp_play(mp);
}

static void pause(GtkWidget *widget, gpointer data) {
	mp_t *mp = data;
	if (!mp_is_playing(mp)) return;
	mp_pause(mp);
}

static void stop(GtkWidget *widget, gpointer data) {
	mp_t *mp = data;
	if (mp_is_playing(mp)) mp_stop(mp);
}

int main(int argc, char** argv) {
	mp = mp_new();

	XInitThreads();
	gtk_init(&argc, &argv);
	gdk_gl_init(&argc, &argv);

	window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
	gtk_window_set_default_size (GTK_WINDOW (window), 320, 240);
	g_signal_connect(G_OBJECT(window), "destroy", G_CALLBACK(destroy), mp);

	vbox = gtk_vbox_new(FALSE, 0);
	gtk_container_add(GTK_CONTAINER(window), vbox);

	hbox = gtk_hbox_new(FALSE, 0);
	gtk_box_pack_start(GTK_BOX(vbox), hbox, TRUE, TRUE, 0);
	gtk_box_set_child_packing(GTK_BOX(vbox), hbox, FALSE, FALSE, 0, GTK_PACK_START);

	button = gtk_button_new_with_label("Open");
	g_signal_connect(G_OBJECT (button), "clicked", G_CALLBACK(open), mp);
	gtk_box_pack_start(GTK_BOX(hbox), button, TRUE, TRUE, 0);
	gtk_widget_show(button);

	button = gtk_button_new_with_label("Play");
	g_signal_connect(G_OBJECT (button), "clicked", G_CALLBACK(play), mp);
	gtk_box_pack_start(GTK_BOX(hbox), button, TRUE, TRUE, 0);
	gtk_widget_show(button);

	button = gtk_button_new_with_label("Pause");
	g_signal_connect(G_OBJECT (button), "clicked", G_CALLBACK(pause), mp);
	gtk_box_pack_start(GTK_BOX(hbox), button, TRUE, TRUE, 0);
	gtk_widget_show(button);

	button = gtk_button_new_with_label("Stop");
	g_signal_connect(G_OBJECT (button), "clicked", G_CALLBACK(stop), mp);
	gtk_box_pack_start(GTK_BOX(hbox), button, TRUE, TRUE, 0);
	gtk_widget_show(button);

	gtk_widget_show(hbox);
	gtk_widget_show(vbox);
	gtk_widget_show(window);

	gtk_main();
	return 0;
}
